package grobit.torrent

import grobit.tracker.Peer
import grobit.tracker.TrackerResponse
import grobit.wire.PeerConnection

/**
 * Manages a group of connections which are working on the same torrent.
 */
class ConnectionManager {
    private List connections = []
    MetaInfo metaInfo

    void processTrackerResponse(TrackerResponse trackerResponse) {
        trackerResponse.peers.each { peer ->
            registerPeer(peer)
        }
    }

    void registerPeer(Peer peer) {
        println "Registering peer: $peer.address"
        PeerConnection connection = new PeerConnection(peer: peer, metaInfo: metaInfo, connectionManager: this)
        connection.connect()
        if(connection.isConnected()) {
            connection.sendHandshake()
            connections += connection
        }
    }

    /**
     * Called by a connection when it gets updated connection information.
     */
    void availabilityChanged(PeerConnection peerConnection) {
        if( ! peerConnection.busy) {
            int piece = peerConnection.requestNextPiece()
            println "Piece $piece requested from $peerConnection.cId"
        }
    }
}
